/**
 * This file is Copyright © 2008 Software Craftsmen Limited. All Rights Reserved.
 */
package com.softwarecraftsmen.orogeny.buildEnvironments;

import com.softwarecraftsmen.orogeny.BaseDirectory;
import com.softwarecraftsmen.orogeny.BuildScript;
import com.softwarecraftsmen.orogeny.filing.AbsoluteDirectory;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.nio.file.Path;

import static com.softwarecraftsmen.orogeny.filing.AbsoluteDirectory.absoluteDirectory;
import static com.softwarecraftsmen.orogeny.filing.fileSystems.AbstractFileSystem.CurrentFileSystem;

public class BaseDirectoryProcessor
{
	private final Class<? extends BuildScript> buildScript;

	public BaseDirectoryProcessor(final @NotNull Class<? extends BuildScript> buildScript)
	{
		this.buildScript = buildScript;
	}

	@NotNull
	public AbsoluteDirectory currentBuildDirectory(final @NotNull AbsoluteDirectory originalBuildDirectory)
	{
		final String buildDirectoryPathModification = getBuildDirectoryPathModification();
		if (buildDirectoryPathModification.startsWith("/"))
		{
			return absoluteDirectory(CurrentFileSystem, new File(buildDirectoryPathModification));
		}

		final File file = originalBuildDirectory.toFile();
		final Path resolved = file.toPath().resolve(buildDirectoryPathModification);

		return absoluteDirectory(CurrentFileSystem, resolved.toFile());
	}

	// This is an offset or absolute path to the location of the build script
	private String getBuildDirectoryPathModification()
	{
		final BaseDirectory annotation = buildScript.getAnnotation(BaseDirectory.class);
		if (annotation != null)
		{
			return annotation.value();
		}
		return ".";
	}
}
